<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, nextTick } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTree, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import { getMenuListApi } from '@/api/menu'
import { RoutetItem } from '@/api/menu/type'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const treeRef = ref<typeof ElTree>()

const formSchema = ref<FormSchema[]>([
  {
    field: 'enabled',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: t('userDemo.disable'),
          value: false
        },
        {
          label: t('userDemo.enable'),
          value: true
        }
      ],
      clearable: false
    }
  },
  {
    field: 'menu',
    label: t('role.menu'),
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex w-full">
                <div class="flex-1">
                  <ElTree
                    ref={treeRef}
                    show-checkbox
                    node-key="name"
                    props={{ children: 'children', label: 'title' }}
                    highlight-current
                    check-strictly
                    expand-on-click-node={false}
                    data={treeData.value}
                    defaultExpandAll
                  >
                    {{
                      default: (data) => {
                        return <span>{data?.data?.title}</span>
                      }
                    }}
                  </ElTree>
                </div>
                <div class="flex-1">
                  {unref(currentTreeData) && unref(currentTreeData)?.permissionList ? (
                    <ElCheckboxGroup v-model={unref(currentTreeData).meta.permission}>
                      {unref(currentTreeData)?.permissionList.map((v: any) => {
                        return <ElCheckbox label={v.value}>{v.label}</ElCheckbox>
                      })}
                    </ElCheckboxGroup>
                  ) : null}
                </div>
              </div>
            </>
          )
        }
      }
    }
  }
])

const currentTreeData = ref()
// const nodeCheck = (treeData: RoutetItem, choose: boolean) => {
//   currentTreeData.value = treeData
//   console.log(treeData)
// }

const rules = reactive({
  roleName: [required()],
  role: [required()],
  status: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const treeData = ref<RoutetItem[]>([])

const setEnabled = (includes: string[]) => {
  for (const route of includes) {
    unref(treeRef)!.setChecked(route, true, true)
  }
}
const getMenuList = async () => {
  const res = await getMenuListApi(props.currentRow.role)
  if (res) {
    const setTitle = (node: RoutetItem) => {
      const meta = JSON.parse(node.meta)
      node['title'] = meta.title
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          const child = node.children[i]
          child['disabled'] = true
          setTitle(child)
          if (child['props']) {
            node.children.splice(i, 1);
            i--
          }
        }
        if (node.children.length == 1) {
          node['title'] = node.children[0]['title']
          node.children.splice(0, 1);
        }
      }
    }

    for (const node of res.data.list) {
      setTitle(node)
      treeData.value.push(node)
    }
    await nextTick(() => setEnabled(res.data.includes))
  }
}
getMenuList()

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const checkedKeys = unref(treeRef)?.getCheckedKeys() || []
    formData.routes = checkedKeys || []
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<style lang="scss">
.is-checked .el-checkbox__inner {
  background-color: var(--el-color-primary) !important;
}

.is-checked .el-checkbox__inner::after {
  border-color: var(--el-color-white) !important;
}
</style>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
